﻿using IRUM.TR;
using IRUM.Utils;
using IRUM.XingAPI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace IRUM.UI
{
    public partial class FormEveningMarket : Form
    {
        ThreadEveningMarket thread = null;
        ThreadStart tStart = null;
        Thread threadEvening = null;
        private SessionCtrl m_session = new SessionCtrl();

        public FormEveningMarket()
        {
            InitializeComponent();
        }

        private void FormEveningMarket_Load(object sender, EventArgs e)
        {
            LoginDialog dlg = new LoginDialog(m_session);

            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                this.Close();
            }

            thread = new ThreadEveningMarket(this);

            //Thread 시작
            tStart = new ThreadStart(thread.Start);
            threadEvening = new Thread(tStart);
            threadEvening.Start();

            btnQuery.Enabled = false;
        }

        private void FormEveningMarket_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (threadEvening != null)
            {
                threadEvening.Abort();
                threadEvening = null;
                tStart = null;
                thread = null;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            bool isCompleted = true;

            if (pbFutureMin.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbFutureDay.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbOptionMin.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbOptionDay.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbInvestorTradeMin.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbInvestorTradeDay.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbOpenYak.Value < 100)
            {
                isCompleted = false;
            }

            if (isCompleted == true && pbForeignChart.Value < 100)
            {
                isCompleted = false;
            }




            if (isCompleted == true)
            {
                timer1.Enabled = false;

                if (threadEvening != null)
                {
                    threadEvening.Abort();
                    threadEvening = null;
                    tStart = null;
                    thread = null;

                    m_session.m_Session.Logout();
                    m_session.m_Session.DisconnectServer();
                }

                this.Close();
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            //Thread 시작
            tStart = new ThreadStart(thread.Start);
            threadEvening = new Thread(tStart);
            threadEvening.Start();
        }

        private delegate void ProgressDisplay(int value);

        public void SetProgressOptionMin(int value)
        {
            if (pbOptionMin.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressOptionMin);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbOptionMin.Value = value;
            }
        }

        public void SetProgressOptionDay(int value)
        {
            if (pbOptionDay.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressOptionDay);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbOptionDay.Value = value;
            }
        }

        public void SetProgressFutureMin(int value)
        {
            if (pbFutureMin.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressFutureMin);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbFutureMin.Value = value;
            }
        }

        public void SetProgressFutureDay(int value)
        {
            if (pbFutureDay.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressFutureDay);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbFutureDay.Value = value;
            }
        }

        public void SetProgressInvestorTradeMin(int value)
        {
            if (pbInvestorTradeMin.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressInvestorTradeMin);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbInvestorTradeMin.Value = value;
            }
        }

        public void SetProgressInvestorTradeDay(int value)
        {
            if (pbInvestorTradeDay.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressInvestorTradeDay);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbInvestorTradeDay.Value = value;
            }
        }

        public void SetProgressOpenYak(int value)
        {
            if (pbOpenYak.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressOpenYak);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbOpenYak.Value = value;
            }
        }

        public void SetProgressForeignChart(int value)
        {
            if (pbForeignChart.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressForeignChart);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbForeignChart.Value = value;
            }
        }

        public void SetProgressForeignFutureDay(int value)
        {
            if (pbForeignFutureDay.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressForeignFutureDay);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbForeignFutureDay.Value = value;
            }
        }

        public void SetProgressForeignFutureMin(int value)
        {
            if (pbForeignFutureMin.InvokeRequired)
            {
                ProgressDisplay printer = new ProgressDisplay(SetProgressForeignFutureMin);
                this.Invoke(printer, new object[] { value });
            }
            else
            {
                pbForeignFutureMin.Value = value;
            }
        }
    }

    /// <summary>
    /// 야간 장 정보수집 - 수급, 차트, 미결제약정, 해외지수
    /// 차트, 수급, 미결제약정의 경우 주간과 야간을 별도의 테이블에 저장해야 함.
    /// 차트
    ///       t8429 야간옵션 분봉
    ///       t2833 야간옵션 일봉
    ///       t8408 야간선물 분봉
    ///       t2805 야간선물 일봉
    /// 수급
    ///       t2814 기간별 투자자
    ///       t2813 시간대별 투자자(30초)
    /// 미결제약정
    ///       t8409 일/분
    /// 해외지수
    ///       t3518 일/분
    ///   KIND(Length:1) S:해외지수, F:해외선물, R:환율/금리
    ///   SYMBOL(Length: 16)
    ///    - 해외지수
    ///       DJI@DJI         : 다우산업
    ///       NAS@IXIC        : 나스닥 종합
    ///       SPI@SPX         : S&P 500
    ///       USI@SOXX        : 필라델피아 반도체
    ///       NII@NI225       : 니케이 225
    ///       TWS@TI01        : 대만 가권
    ///       SHS@000002      : 상해 A
    ///       SHS@000003      : 상해 B
    ///       SGI@STI         : 싱가폴 STI
    ///    - 해외선물
    ///       NQM14           : E-mini NASDAQ 100(2014.06월물) - 순서대로 월을 표시함 FGHJKMNQUVXZ
    ///       NQ.1            : E-mini NASDAQ 100(연결)
    ///       ES.1            : E-mini S&P 500(연결)
    ///       YM.1            : Mini Dow(연결)
    ///       FDAX.1          : DAX(연결)
    ///       FFI.1           : FTSE100(연결)
    ///    - 환율/금리
    ///       JPYKRWCOMP      : 한국 원/일본 엔
    ///       KRWCNYCOMP      : 중국 위안/한국 원
    ///       USDCNYCOMP      : 중국 위안/달러
    ///       USDEURCOMP      : 유로/달러
    ///       USDGBPCOMP      : 영국 파운드/달러
    ///       USDJPYCOMP      : 일본 엔/달러
    ///       USDKRWSMBS      : 원/달러
    /// </summary>
    class ThreadEveningMarket
    {
        FormEveningMarket form = null;

        int totalOptionCodeCount = 0;
        int totalFutureCodeMinCount = 0;
        int totalOpenYakCount = 0;
        int totalForeignChart = 0;
        int totalForeignFutureChart = 0;

        t2833 eveningOptionDay = null;
        t8429 eveningOptionMin = null;
        t2805 eveningFutureDay = null;
        t8408 eveningFutureMin = null;
        t2814 eveningInvestorTradeDay = null;
        t2813 eveningInvestorTradeMin = null;
        t8409 eveningOpenYak = null;
        t3518 foreignChart = null;
        o3104 foreignFutureDay = null;
        //o3103 foreignFutureMin = null;


        Queue<string> qCodeOptionMin = new Queue<string>();
        Queue<string> qCodeOptionDay = new Queue<string>();
        Queue<string> qCodeFuture = new Queue<string>();
        Queue<string> qCodeOpenYak = new Queue<string>();
        Queue<ForeignSymbol> qSymbolForeign = new Queue<ForeignSymbol>();
        Queue<ForeignSymbol> qSymbolForeignFutureDay = new Queue<ForeignSymbol>();
        Queue<ForeignSymbol> qSymbolForeignFutureMin = new Queue<ForeignSymbol>();
        string codeFutureDaily = string.Empty;              //야간선물 일봉조회용

        public ThreadEveningMarket(FormEveningMarket form)
        {
            this.form = form;


            IRUMDataClassesDataContext dc = new IRUMDataClassesDataContext();
            DateTime lastDate = IRUM_Utils.GetLastTradingDateEvening(DateTime.Now);     //마지막 야간 거래일 - 전일정보를 가져오는 것


            //옵션 본월물 이후의 모든 종목코드 가져와서 종목코드큐에 넣어주기
            DateTime closingDateOfOption = IRUM_Utils.GetClosingDateOfOption(lastDate);         //마지막 야간 거래일 기준 옵션 만기일 - 전일기준으로 만기일을 가져와야 함.
            List<string> lstCodeOption = dc.ProdCodes.Where(p => p.kind.Equals("O") && Convert.ToInt32(p.expire) >= Convert.ToInt32(closingDateOfOption.ToString("yyyyMM"))).Select(p => p.shcode).ToList<string>();

            totalOptionCodeCount = lstCodeOption.Count;
            foreach (string code in lstCodeOption)
            {
                qCodeOptionMin.Enqueue(code);
                qCodeOptionDay.Enqueue(code);
            }


            //선물 본월물 이후의 모든 종목코드 가져와서 종목코드큐에 넣어주기
            DateTime closingDateOfFuture = IRUM_Utils.GetClosingDateOfFuture(lastDate);         //마지막 야간 거래일 기준 옵션 만기일 - 전일기준으로 만기일을 가져와야 함.
            List<string> lstCodeFuture = dc.ProdCodes.Where(p => p.kind.Equals("F") && Convert.ToInt32(p.expire) >= Convert.ToInt32(closingDateOfFuture.ToString("yyyyMM"))).Select(p => p.shcode).ToList<string>();
            codeFutureDaily = lstCodeFuture[0];

            totalFutureCodeMinCount = lstCodeFuture.Count;
            totalOpenYakCount = lstCodeFuture.Count;
            foreach (string code in lstCodeFuture)
            {
                qCodeFuture.Enqueue(code);
                qCodeOpenYak.Enqueue(code);
            }


            //해외지수 종목코드
            List<ForeignSymbol> lstSymbolForeign = dc.ForeignSymbols.Where(p => p.kind.Equals("S") || p.kind.Equals("R")).Select(p => p).ToList();
            totalForeignChart = lstSymbolForeign.Count;

            foreach (ForeignSymbol fs in lstSymbolForeign)
            {
                qSymbolForeign.Enqueue(fs);
            }

            //해외선물 종목코드
            List<ForeignSymbol> lstSymbolForeignFuture = dc.ForeignSymbols.Where(p => p.kind.Equals("F")).Select(p => p).ToList();
            totalForeignFutureChart = lstSymbolForeignFuture.Count;

            foreach (ForeignSymbol fs in lstSymbolForeignFuture)
            {
                qSymbolForeignFutureDay.Enqueue(fs);
                qSymbolForeignFutureMin.Enqueue(fs);
            }
        }


        public void Start()
        {
            //야간선물 일봉조회
            QueryEveningFutureDay();

            //야간선물 분봉조회
            QueryEveningFutureMinute();

            //야간수급 기간별
            QueryEveningInvestorTradeDaily();
        }


        #region 야간옵션 차트조회
        /// <summary>
        /// 야간옵션 분봉조회
        /// </summary>
        private void QueryEveningOptionMinute()
        {
            if (qCodeOptionMin.Count > 0)
            {
                Thread.Sleep(1000);
                eveningOptionMin = new t8429(qCodeOptionMin.Dequeue());
                eveningOptionMin.OnReceived += eveningOptionMin_OnReceived;
                eveningOptionMin.Request();
            }
        }

        void eveningOptionMin_OnReceived(object s, ChartDataArgs e)
        {
            foreach (ChartData c in e.RetData)
            {
                form.chartDataEveningTableAdapter.sp_ChartDataEvening_i(c.shcode, c.gubun, c.date, c.time, c.open, c.high, c.low, c.close, c.jdiff_vol, c.openyak);
            }
            e.RetData.Clear();

            form.SetProgressOptionMin(Convert.ToInt32(Convert.ToSingle(totalOptionCodeCount - qCodeOptionMin.Count) / totalOptionCodeCount * 100));

            if (qCodeOptionMin.Count > 0)
            {
                QueryEveningOptionMinute();
            }
            else
            {
                chartDataEveningBindingNavigatorSaveItem();
            }
        }

        /// <summary>
        /// 야간옵션 일봉조회
        /// </summary>
        private void QueryEveningOptionDaily()
        {
            if (qCodeOptionDay.Count > 0)
            {
                string shcode = qCodeOptionDay.Dequeue();
                IRUMDataClassesDataContext dc = new IRUMDataClassesDataContext();
                string lastDBDate = "0";

                if (dc.ChartDataEvenings.Where(p => p.gubun.Equals("D") && p.shcode.Equals(shcode)).Count() > 0)
                {
                    List<string> lstDate = dc.ChartDataEvenings.Where(p => p.gubun.Equals("D") && p.shcode.Equals(shcode)).Select(p => p.date).ToList();
                    string strMaxDate = lstDate.Max();
                    DateTime maxDate = new DateTime(Convert.ToInt32(strMaxDate.Substring(0, 4)), Convert.ToInt32(strMaxDate.Substring(4, 2)), Convert.ToInt32(strMaxDate.Substring(6, 2)));
                    lastDBDate = maxDate.AddDays(-5).ToString("yyyyMMdd");
                }
                
                Thread.Sleep(1000);
                eveningOptionDay = new t2833(shcode, lastDBDate);
                eveningOptionDay.OnReceived += eveningOptionDay_OnReceived;
                eveningOptionDay.Request();
            }
        }

        void eveningOptionDay_OnReceived(object s, ChartDataArgs e)
        {
            foreach (ChartData c in e.RetData)
            {
                form.chartDataEveningTableAdapter.sp_ChartDataEvening_i(c.shcode, c.gubun, c.date, c.time, c.open, c.high, c.low, c.close, c.jdiff_vol, c.openyak);
            }
            e.RetData.Clear();

            form.SetProgressOptionDay(Convert.ToInt32(Convert.ToSingle(totalOptionCodeCount - qCodeOptionDay.Count) / totalOptionCodeCount * 100));

            if (qCodeOptionDay.Count > 0)
            {
                QueryEveningOptionDaily();
            }
            else
            {
                chartDataEveningBindingNavigatorSaveItem();
            }
        }
        
        #endregion


        #region 야간 미결제약정
        string codeOpenYak = string.Empty;
        string gbnOpenYak = "M";

        /// <summary>
        /// 야간 미결제약정
        /// </summary>
        private void QueryEveningOpenYak()
        {
            Thread.Sleep(1000);
            eveningOpenYak = new t8409(codeOpenYak, gbnOpenYak);
            eveningOpenYak.OnReceived += eveningOpenYak_OnReceived;
            eveningOpenYak.Request();
        }

        void eveningOpenYak_OnReceived(object s, OpenYakArgs e)
        {
            foreach (OpenYak oy in e.RetData)
            {
                form.openYakEveningTableAdapter.sp_OpenYakEvening_i(codeOpenYak, oy.gubun, oy.date, oy.time, oy.openopenyak, oy.highopenyak, oy.lowopenyak, oy.closeopenyak, oy.openupdn);
            }
            e.RetData.Clear();

            // 시간대별 데이터 조회 후 기간별 데이터 조회한 다음 다른 행사가 조회
            if (gbnOpenYak.Equals("M") == true)
            {
                gbnOpenYak = "D";
                QueryEveningOpenYak();
            }
            else
            {
                form.SetProgressOpenYak(Convert.ToInt32(Convert.ToSingle(totalOpenYakCount - qCodeOpenYak.Count) / totalOpenYakCount * 100));

                if (qCodeOpenYak.Count > 0)
                {
                    codeOpenYak = qCodeOpenYak.Dequeue();
                    gbnOpenYak = "M";
                    QueryEveningOpenYak();
                }
                else
                {
                    OpenYakBindingEveningNavigatorSaveItem();

                    //해외지수/선물/환율 조회
                    if (qSymbolForeign.Count > 0)
                    {
                        foreignSymbol = qSymbolForeign.Dequeue();
                        QueryChartForeign();
                    }

                    if (qSymbolForeignFutureDay.Count > 0)
                    {
                        //해외선물
                        QueryChartForeignFutureDaily();
                        QueryChartForeignFutureMinute();
                    }
                }
            }
        }

        #endregion


        #region 야간수급조회
        /// <summary>
        /// 야간 수급조회 - 분단위
        /// </summary>
        private void QueryEveningInvestorTradeMinute()
        {
            eveningInvestorTradeMin = new t2813();
            eveningInvestorTradeMin.OnReceived += eveningInvestorTradeMin_OnReceived;
            eveningInvestorTradeMin.Request();
        }

        void eveningInvestorTradeMin_OnReceived(object s, InvestorTradeArgs e)
        {
            foreach (TR.InvestorTrade it in e.RetData)
            {
                form.investorTradeEveningTableAdapter.sp_InvestorTradeEveningMin_i(it.date, it.gubun, it.time, it.native_sum, it.foreign_sum, it.organization_sum);
            }
            e.RetData.Clear();

            investorTradeBindingEveningNavigatorSaveItem();
            form.SetProgressInvestorTradeMin(100);

            //야간 미결제약정
            if (qCodeOpenYak.Count > 0)
            {
                codeOpenYak = qCodeOpenYak.Dequeue();
                QueryEveningOpenYak();
            }
        }

        /// <summary>
        /// 야간 수급조회 - 일단위
        /// </summary>
        private void QueryEveningInvestorTradeDaily()
        {
            eveningInvestorTradeDay = new t2814();
            eveningInvestorTradeDay.OnReceived += eveningInvestorTradeDay_OnReceived;
            eveningInvestorTradeDay.Request();
        }

        void eveningInvestorTradeDay_OnReceived(object s, InvestorTradeArgs e)
        {
            foreach (TR.InvestorTrade it in e.RetData)
            {
                form.investorTradeEveningTableAdapter.sp_InvestorTradeEveningDay_i(it.date, it.gubun, it.time, it.native_buy, it.native_sell, it.native_sum, it.foreign_buy, it.foreign_sell, it.foreign_sum, it.organization_buy, it.organization_sell, it.organization_sum);
            }
            e.RetData.Clear();

            investorTradeBindingEveningNavigatorSaveItem();
            form.SetProgressInvestorTradeDay(100);

            //야간수급 시간대별
            QueryEveningInvestorTradeMinute();
        }
        #endregion


        #region 야간선물 차트조회
        /// <summary>
        /// 야간선물 분봉조회
        /// </summary>
        private void QueryEveningFutureMinute()
        {
            if (qCodeFuture.Count > 0)
            {
                Thread.Sleep(1000);
                eveningFutureMin = new t8408(qCodeFuture.Dequeue());
                eveningFutureMin.OnReceived += eveningFutureMin_OnReceived;
                eveningFutureMin.Request();
            }
        }

        void eveningFutureMin_OnReceived(object s, ChartDataArgs e)
        {
            foreach (ChartData c in e.RetData)
            {
                form.chartDataEveningTableAdapter.sp_ChartDataEvening_i(c.shcode, c.gubun, c.date, c.time, c.open, c.high, c.low, c.close, c.jdiff_vol, c.openyak);
            }
            e.RetData.Clear();

            form.SetProgressFutureMin(Convert.ToInt32(Convert.ToSingle(totalFutureCodeMinCount - qCodeFuture.Count) / totalFutureCodeMinCount * 100));

            if (qCodeFuture.Count > 0)
            {
                QueryEveningFutureMinute();
            }
            else
            {
                chartDataEveningBindingNavigatorSaveItem();

                //야간옵션 분봉조회
                QueryEveningOptionMinute();
            }
        }

        /// <summary>
        /// 야간선물 일봉조회
        /// </summary>
        private void QueryEveningFutureDay()
        {
            IRUMDataClassesDataContext dc = new IRUMDataClassesDataContext();
            string lastDBDate = "0";

            if (dc.ChartDataEvenings.Where(p => p.gubun.Equals("D") && p.shcode.Equals("99999999")).Count() > 0)
            {
                List<string> lstDate = dc.ChartDataEvenings.Where(p => p.gubun.Equals("D") && p.shcode.Equals("99999999")).Select(p => p.date).ToList();
                string strMaxDate = lstDate.Max();
                DateTime maxDate = new DateTime(Convert.ToInt32(strMaxDate.Substring(0, 4)), Convert.ToInt32(strMaxDate.Substring(4, 2)), Convert.ToInt32(strMaxDate.Substring(6, 2)));
                lastDBDate = maxDate.AddDays(-5).ToString("yyyyMMdd");
            }

            eveningFutureDay = new t2805(codeFutureDaily, lastDBDate);
            eveningFutureDay.OnReceived += eveningFutureDay_OnReceived;
            eveningFutureDay.Request();
        }

        void eveningFutureDay_OnReceived(object s, ChartDataArgs e)
        {
            foreach (ChartData c in e.RetData)
            {
                form.chartDataEveningTableAdapter.sp_ChartDataEvening_i(c.shcode, c.gubun, c.date, c.time, c.open, c.high, c.low, c.close, c.jdiff_vol, c.openyak);
            }
            e.RetData.Clear();

            form.SetProgressFutureDay(100);
            chartDataEveningBindingNavigatorSaveItem();

            //야간옵션 일봉조회
            QueryEveningOptionDaily();
        }
        #endregion


        #region 해외지수/환율
        ForeignSymbol foreignSymbol = null;
        string gbnforeignSymbol = "M";

        /// <summary>
        /// 해외지수
        /// </summary>
        private void QueryChartForeign()
        {
            string lastDBDate = "0";

            if (gbnforeignSymbol.Equals("D"))
            {
                IRUMDataClassesDataContext dc = new IRUMDataClassesDataContext();

                if (dc.ChartDataForeigns.Where(p => p.gubun.Equals("D") && p.shcode.Equals(foreignSymbol.Symbol)).Count() > 0)
                {
                    List<string> lstDate = dc.ChartDataForeigns.Where(p => p.gubun.Equals("D") && p.shcode.Equals(foreignSymbol.Symbol)).Select(p => p.date).ToList();
                    string strMaxDate = lstDate.Max();
                    DateTime maxDate = new DateTime(Convert.ToInt32(strMaxDate.Substring(0, 4)), Convert.ToInt32(strMaxDate.Substring(4, 2)), Convert.ToInt32(strMaxDate.Substring(6, 2)));
                    lastDBDate = maxDate.AddDays(-5).ToString("yyyyMMdd");
                }
            }

            
            Thread.Sleep(1000);
            foreignChart = new t3518(foreignSymbol.kind, foreignSymbol.Symbol, gbnforeignSymbol, lastDBDate);
            foreignChart.OnReceived += foreignChart_OnReceived;
            foreignChart.Request();
        }

        void foreignChart_OnReceived(object s, ChartForeignDataArgs e)
        {
            foreach (ChartForeignData cd in e.RetData)
            {
                form.chartDataForeignTableAdapter.sp_ChartDataForeign_i(cd.kind, cd.shcode, cd.gubun, cd.date, cd.time, cd.open, cd.high, cd.low, cd.close, cd.volume, cd.kodate, cd.kotime);
            }
            e.RetData.Clear();

            // 시간대별 데이터 조회 후 기간별 데이터 조회한 다음 다른 행사가 조회
            if (gbnforeignSymbol.Equals("M") == true)
            {
                gbnforeignSymbol = "D";
                QueryChartForeign();
            }
            else
            {
                form.SetProgressForeignChart(Convert.ToInt32(Convert.ToSingle(totalForeignChart - qSymbolForeign.Count) / totalForeignChart * 100));

                if (qSymbolForeign.Count > 0)
                {
                    foreignSymbol = qSymbolForeign.Dequeue();
                    gbnforeignSymbol = "M";
                    QueryChartForeign();
                }
                else
                {
                    ChartDataForeignBindingEveningNavigatorSaveItem();
                }
            }
        }

        #endregion


        #region 해외선물
        /// <summary>
        /// 해외선물 일차트
        /// </summary>
        private void QueryChartForeignFutureDaily()
        {
            string lastDBDate = "0";
            IRUMDataClassesDataContext dc = new IRUMDataClassesDataContext();
            ForeignSymbol symbol = qSymbolForeignFutureDay.Dequeue();

            if (dc.ChartDataForeigns.Where(p => p.gubun.Equals("D") && p.shcode.Equals(symbol.Symbol)).Count() > 0)
            {
                List<string> lstDate = dc.ChartDataForeigns.Where(p => p.gubun.Equals("D") && p.shcode.Equals(symbol.Symbol)).Select(p => p.date).ToList();
                string strMaxDate = lstDate.Max();
                DateTime maxDate = new DateTime(Convert.ToInt32(strMaxDate.Substring(0, 4)), Convert.ToInt32(strMaxDate.Substring(4, 2)), Convert.ToInt32(strMaxDate.Substring(6, 2)));
                lastDBDate = maxDate.AddDays(-5).ToString("yyyyMMdd");
            }


            Thread.Sleep(1000);
            foreignFutureDay = new o3104(symbol.Symbol, lastDBDate);
            foreignFutureDay.OnReceived += foreignFutureDay_OnReceived;
            foreignFutureDay.Request();
        }

        void foreignFutureDay_OnReceived(object s, ChartForeignDataArgs e)
        {
            foreach (ChartForeignData cd in e.RetData)
            {
                form.chartDataForeignTableAdapter.sp_ChartDataForeign_i(cd.kind, cd.shcode, cd.gubun, cd.date, cd.time, cd.open, cd.high, cd.low, cd.close, cd.volume, cd.kodate, cd.kotime);
            }
            e.RetData.Clear();

            form.SetProgressForeignFutureDay(Convert.ToInt32(Convert.ToSingle(totalForeignFutureChart - qSymbolForeignFutureDay.Count) / totalForeignFutureChart * 100));

            if (qSymbolForeignFutureDay.Count > 0)
            {
                QueryChartForeignFutureDaily();
            }
            else
            {
                ChartDataForeignBindingEveningNavigatorSaveItem();
            }
        }

        /// <summary>
        /// 해외선물 분차트
        /// </summary>
        private void QueryChartForeignFutureMinute()
        {
            string lastDBDate = "0";
            IRUMDataClassesDataContext dc = new IRUMDataClassesDataContext();
            ForeignSymbol symbol = qSymbolForeignFutureMin.Dequeue();

            if (dc.ChartDataForeigns.Where(p => p.gubun.Equals("M") && p.shcode.Equals(symbol.Symbol)).Count() > 0)
            {
                List<string> lstDate = dc.ChartDataForeigns.Where(p => p.gubun.Equals("M") && p.shcode.Equals(symbol.Symbol)).Select(p => p.date).ToList();
                string strMaxDate = lstDate.Max();
                DateTime maxDate = new DateTime(Convert.ToInt32(strMaxDate.Substring(0, 4)), Convert.ToInt32(strMaxDate.Substring(4, 2)), Convert.ToInt32(strMaxDate.Substring(6, 2)));
                lastDBDate = maxDate.AddDays(-5).ToString("yyyyMMdd");
            }


            //Thread.Sleep(1000);
            //foreignFutureMin = new o3103(symbol.Symbol, lastDBDate);
            //foreignFutureMin.OnReceived += foreignFutureMin_OnReceived;
            //foreignFutureMin.Request();
        }

        void foreignFutureMin_OnReceived(object s, ChartForeignDataArgs e)
        {
            foreach (ChartForeignData cd in e.RetData)
            {
                form.chartDataForeignTableAdapter.sp_ChartDataForeign_i(cd.kind, cd.shcode, cd.gubun, cd.date, cd.time, cd.open, cd.high, cd.low, cd.close, cd.volume, cd.kodate, cd.kotime);
            }
            e.RetData.Clear();

            form.SetProgressForeignFutureMin(Convert.ToInt32(Convert.ToSingle(totalForeignFutureChart - qSymbolForeignFutureMin.Count) / totalForeignFutureChart * 100));

            if (qSymbolForeignFutureMin.Count > 0)
            {
                QueryChartForeignFutureMinute();
            }
            else
            {
                ChartDataForeignBindingEveningNavigatorSaveItem();
            }
        }

        #endregion


        #region DB 반영
        /// <summary>
        /// 차트데이터 저장
        /// </summary>
        private void chartDataEveningBindingNavigatorSaveItem()
        {
            form.chartDataEveningBindingSource.EndEdit();
            form.tableAdapterManager.UpdateAll(form.iRUMDataSet);
        }

        /// <summary>
        /// 수급데이터 저장
        /// </summary>
        private void investorTradeBindingEveningNavigatorSaveItem()
        {
            form.investorTradeEveningBindingSource.EndEdit();
            form.tableAdapterManager.UpdateAll(form.iRUMDataSet);
        }

        /// <summary>
        /// 미결제약정데이터 저장
        /// </summary>
        private void OpenYakBindingEveningNavigatorSaveItem()
        {
            form.openYakEveningBindingSource.EndEdit();
            form.tableAdapterManager.UpdateAll(form.iRUMDataSet);
        }

        /// <summary>
        /// 해외지수 차트데이터 저장
        /// </summary>
        private void ChartDataForeignBindingEveningNavigatorSaveItem()
        {
            form.chartDataForeignBindingSource.EndEdit();
            form.tableAdapterManager.UpdateAll(form.iRUMDataSet);
        }
        #endregion
    }
}
